package com.jt.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 金帮嘉诚 @date 2021-08-20 星期五 20:21
 * sentinel默认的异常提示继承了BlockExceptionHandler接口
 * 我们可以自己实现该接口 并加@Component注解 这样可以替代默认的处理方法
 * (之所以可以替代 是因为默认的实现类上
 * 使用了@ConditionalOnMissingBean(BlockExceptionHandler.class))
 */
@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       BlockException e) throws Exception {
//        response.setContentType("text/html;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        out.println("??????遇见了某个错误?????");
        Map<String, Object> map = new HashMap<>();
        if (e instanceof DegradeException) {
            map.put("statue", "601");
            map.put("message", "服务被熔断了");
        } else if (e instanceof FlowException) {
            map.put("statue", "602");
            map.put("message", "服务被限流了");
        } else {
            map.put("statue", "603");
            map.put("message", "服务被sentinel限制了");
        }
        String jsonString = new ObjectMapper().writeValueAsString(map);

        out.println(jsonString);

//        String msg="";
//        if (e instanceof FlowException) {
//            msg = "限流了";
//        } else if (e instanceof DegradeException) {
//            msg = "降级了";
//        } else if (e instanceof ParamFlowException) {
//            msg = "热点参数限流";
//        } else if (e instanceof SystemBlockException) {
//            msg = "系统规则（负载/...不满足要求）";
//        } else if (e instanceof AuthorityException) {
//            msg = "授权规则不通过";
//        }
//        out.println(msg);

//————————————————
//        版权声明：本文为CSDN博主「放飞的承诺」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//        原文链接：https://blog.csdn.net/u011684553/article/details/108789968
        out.flush();
        out.close();

    }
}
